<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="110px">
      <el-form-item label="资讯名称" prop="title">
        <el-input v-model="dataForm.title" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item label="资讯分类" prop="type">
        <el-select v-model="dataForm.dicId" clearable placeholder="分类" style="width: 100%">
          <el-option v-for="(item,index) in typeList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主图" prop="imgUrl">
        <div class="item-r img_sky_wrapper">
          <div class="img_sky" v-if="dataForm.imgUrl != '' && dataForm.imgUrl != null" v-model="dataForm.imgUrl">
            <img :src="baseImageUrl + dataForm.imgUrl" alt />
            <el-button class="deleteImg" @click="deleteImg()" type="danger" icon="el-icon-delete" circle></el-button>
          </div>
          <div class="img_sky">
            <el-upload
              style="text-align:center"
              class="avatar-uploader"
              :action="actionUpload"
              :headers="{'current-service':'1'}"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              v-loading="loading"
            >
              <img width="100%" src="../../../assets/img/add.jpg" alt />
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="内容">
        <template>
          <div>
            <el-upload
              class="avatar-uploader edFile"
              :action="actionUpload"
              :headers="{'current-service':'1'}"
              name="img"
              :data="fileUpload"
              :show-file-list="false"
              :on-success="uploadEdSuccess"
              :on-error="uploadEdError"
              :before-upload="beforeEdUpload"
            ></el-upload>
            <quill-editor
              class="ql-editor-class"
              v-model="dataForm.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)"
            ></quill-editor>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序"></el-input-number>
      </el-form-item>
    </el-form>
    <br />
    <br />
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import Editor from '@tinymce/tinymce-vue'
import { quillEditor } from 'vue-quill-editor' //调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Quill from 'quill' // 富文本基于quill
import Parchment from 'parchment'

//默认有工具栏，如果想自定义工具栏可以在toolbarOptions配置，不需要的删掉即可
//想直接使用默认的工具栏删掉editorOption中的modules->toolbar即可
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
  ['blockquote', 'code-block'], //引用，代码块

  [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
  [{ list: 'ordered' }, { list: 'bullet' }], //列表
  [{ script: 'sub' }, { script: 'super' }], // 上下标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  [{ direction: 'rtl' }], // 文本方向

  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题

  [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
  [{ font: [] }], //字体
  [{ align: [] }], //对齐方式

  ['clean'], //清除字体样式
  ['image', 'video'] //上传图片、上传视频
]
//目的是修改富文本内容居中不了的问题
let config = {
  scope: Parchment.Scope.BLOCK,
  whitelist: ['right', 'center', 'justify']
}
let AlignStyle = new Parchment.Attributor.Style('align', 'text-align', config)
export { AlignStyle }
var Align = Quill.import('attributors/style/align')
Align.whitelist = ['right', 'center', 'justify']

export default {
  components: { quillEditor },
  data() {
    return {
      actionUpload: 'http://192.168.101.128:8080',
      visible: false,
      dataForm: {
        id: 0,
        title: '',
        imgUrl: '',
        content: '',
        type: [],
        dicId:'',
        status: 1,
        sort: 0
      },
      dataRule: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '详情不能为空', trigger: 'blur' }]
      },
      typeList: [],
      fileUpload: {
        //附件上传
        file: null
      },
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector('.edFile input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        },
        placeholder: '详情',
        theme: 'snow' //默认即是snow
      },
      loading:false
    }
  },
  mounted() {
    this.actionUpload = this.$http.adornUrl(`/common/file/upload?token=${this.$cookie.get('token')}`)
  },
  created(){
    this.getTypeList()
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0
      this.visible = true
      if (this.dataForm.id) {
        this.$http({
          url: this.$http.adornUrl(`/ad/info/${this.dataForm.id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            let info = data.info
            this.dataForm.title = info.title
            this.dataForm.imgUrl = info.img
            this.dataForm.content = info.content
            this.dataForm.sort = info.sort
            this.dataForm.status = info.status
            this.dataForm.dicId = info.dicId
          }
        })
      } else {
        this.$refs['dataForm'].resetFields()
        this.dataForm.content = ''
      }
    },
    // 资讯类型
    getTypeList() {
      this.$http({
        url: this.$http.adornUrl('/dictionary/listByType'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: 100,
          type:'infoType'
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.typeList = data.page.list
        } else {
          this.typeList = []
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      if (res.code == 200) {
        const imgUrl = res.msg[0]
        this.dataForm.imgUrl = imgUrl
      }
    },
    beforeAvatarUpload(file) {
      let isLt10M = file.size / 1024 / 1024 < 10 //设定图片上传 大小限制
      let reg = /\.(jpg|jpeg|png)$/i
      if (!reg.test(file.name)) {
        this.$message({
          showClose: true,
          message: '上传支持格式（.jpg/.jpeg/.png）',
          type: 'error'
        })
        return false
      } else if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
        return false
      }
    },
    deleteImg() {
      this.dataForm.imgUrl = ''
    },
    uploadEdError() {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    uploadEdSuccess(res, file) {
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.myQuillEditor.quill
      console.log('富文本图片：' + res)
      // 上传成功所执行
      if (res.code == '0' && res.data !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index
        // 插入图片res为服务器返回的数据
        quill.insertEmbed(length, 'image', this.baseImageUrl + res.data)
        // 光标移动至文本末端
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    beforeEdUpload(file) {
      this.fileUpload.file = file
      // 显示loading动画
      this.quillUpdateImg = true
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/ad/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              title: this.dataForm.title,
              content: this.dataForm.content,
              img: this.dataForm.imgUrl,
              content: this.content,
              status: this.dataForm.status, //0-禁用 1-启用
              sort: this.dataForm.sort,
              type:1, //1-资讯 2-广告
              // url:this.dataForm.url 跳转路径
              dicId:this.dataForm.dicId
              // dicName:null 类型名称
              // userName:null 发布人
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    onEditorBlur(quill) {
      // console.log("editor blur!", quill);
    },
    onEditorFocus(quill) {
      // console.log("editor focus!", quill);
    },
    onEditorReady(quill) {
      // console.log("editor ready!", quill);
    },
    onEditorChange({ quill, html, text }) {
      // console.log("editor change!", quill, html, text);
      this.content = html
    },
    mounted() {
      // console.log("this is current quill instance object", this.editor);
    },
    computed: {
      editor() {
        return this.$refs.myQuillEditor.quill
      }
    }
  }
}
</script>

<style>
/* .quill-editor{
     height: 200px;
 } */

.ql-editor {
  min-height: 200px;
}

.img_sky {
  width: 100px;
  height: 100px;
  border: 1px solid #fff;
  position: relative;
  overflow: hidden;
}
.img_sky > img {
  width: 100%;
  height: 100%;
  cursor: pointer;
}
.img_sky_wrapper {
  display: flex;
  flex-wrap: wrap;
}
.config-r .item-l {
  width: 100px;
}
.deleteImg {
  position: absolute;
  top: 0;
  right: 0;
  display: none;
  font-size: 16px;
  opacity: 0.8;
  padding: 5px !important;
}
.img_sky:hover .deleteImg {
  display: block;
}
.img_sky img {
  transition: all 0.5s;
}
.img_sky:hover img {
  transform: scale(1.2, 1.2);
}
.el-upload {
  font-size: 30px;
}
.ql-editor-class {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: 1;
  height: 100%;
  outline: none;
  padding: 0 !important;
  tab-size: 4;
  -moz-tab-size: 4;
  text-align: left;
  word-wrap: break-word;
}
</style>
